package org.finesys.common.core.support.concurrent;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class AsyncThreadPool {

    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    private static final int MAX_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int WORK_QUEUE_CAPACITY = 1024;
    private static final long KEEP_ALIVE_TIME = 30L;
    volatile private static ThreadPoolExecutor executor = null;

    public static ThreadPoolExecutor getThreadPool() {
        if (executor == null) {
            return new ThreadPoolExecutor(
                    CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
                    new LinkedBlockingDeque<>(WORK_QUEUE_CAPACITY), new NamedThreadFactory("async-pool"));
        }
        return executor;
    }

    public static void execute(Runnable runnable) {
        getThreadPool().execute(runnable);
    }
}

